package cn.learn.activiti.controller;

import cn.learn.activiti.service.IDeploymentService;
import cn.learn.activiti.util.RestResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 部署流程接口管理
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年03月04日10:19
 */
@Slf4j
@RequiredArgsConstructor
@RequestMapping(path = "/activity/deployment")
@RestController
public class DeploymentController {

    private final IDeploymentService deploymentService;

    /**
     * bpmn20.xml , bpmn文件格式
     */
    @CrossOrigin(origins = "*",maxAge = 3600)
    @PostMapping
    public RestResponse deployment(String stringBPMN) {
        String name = "test33.bpmn";
        Deployment deploy = deploymentService.deploy(stringBPMN, name);
        return RestResponse.success(deploy);
    }

    /**
     * 获取 定义流程
     */
    @GetMapping("/{processDefinitionId}")
    public RestResponse processDefinition(@PathVariable String processDefinitionId) {
        ProcessDefinition   processDefinition = deploymentService.getProcessDefinitionById(processDefinitionId);
        Map<String, Object> map               = new HashMap<>();
        map.put("id", processDefinition.getId());
        map.put("key", processDefinition.getKey());
        map.put("name", processDefinition.getName());
        map.put("version", processDefinition.getVersion());
        map.put("deploymentId", processDefinition.getDeploymentId());
        return RestResponse.success(map);
    }

    @GetMapping("/resource/{processDefinitionId}")
    public RestResponse getResource(@PathVariable String processDefinitionId) {
        try (InputStream resource = deploymentService.getResource(processDefinitionId)) {
            String s = IOUtils.toString(resource, "UTF-8");
            return RestResponse.success(s);
        } catch (Exception e) {
            return RestResponse.failed("", "");
        }
    }


}
